﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Pay.Core {
	public class XmlHelper {
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding, bool is_update = true) {
            if (o == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            string xml = "";
            try {
                using (MemoryStream stream = new MemoryStream()) {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Encoding = encoding;

                    //OmitXmlDeclaration表示不生成声明头，默认是false，OmitXmlDeclaration为true，会去掉<?xml version="1.0" encoding="UTF-8"?>
                    //settings.OmitXmlDeclaration = true;

                    XmlWriter writer = XmlWriter.Create(stream, settings);

                    if (!is_update) {
                        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                        ns.Add("", "");
                        XmlSerializer serializer = new XmlSerializer(o.GetType());
                        serializer.Serialize(writer, o, ns);
                    } else {
                        //强制指定命名空间，覆盖默认的命名空间，可以添加多个，如果要在xml节点上添加指定的前缀，可以在跟节点的类上面添加[XmlRoot(Namespace = "http://www.w3.org/2001/XMLSchema-instance", IsNullable = false)]，Namespace指定哪个值，xml节点添加的前缀就是哪个命名空间(这里会添加ceb)
                        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                        namespaces.Add("ceb", "http://www.china-xmftz.gov.cn/ceb");
                        namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                        XmlSerializer serializer = new XmlSerializer(o.GetType());
                        serializer.Serialize(writer, o, namespaces);
                    }
                    
                    writer.Close();

                    stream.Position = 0;
                    using (StreamReader reader = new StreamReader(stream, encoding)) {
                        xml = reader.ReadToEnd();
                    }
                }
            } catch (Exception ex) {

            }
            return xml;
        }
        /// <summary>
        /// 从XML字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="s">包含对象的XML字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize<T>(string s, Encoding encoding) {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentNullException("s");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer mySerializer = new XmlSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s))) {
                using (StreamReader sr = new StreamReader(ms, encoding)) {
                    return (T)mySerializer.Deserialize(sr);
                }
            }
        }
        /// <summary>
        /// 保存xml文件
        /// </summary>
        /// <param name="xml">Xml.</param>
        /// <param name="path">Path.</param>
        public static void XmlSave(string xml, string path) {
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.LoadXml(xml);
			xmlDocument.Save(path);
		}
	}
}
